var Global = require("../util/global.js");
var message = require("../util/message.js");

cc.Class({
    extends: cc.Component,

    properties: {
        bg:{
            type:cc.Sprite,
            default:null,
        },
        process:{
            type:cc.ProgressBar,
            default:null,
        },
        speed:0,
        isLoading:true,
        isSend:false,
        isReady:false,
        isGame:false,
        loadingText:{
            type:cc.Label,
            default:null,
        },
        updateIndex:0,
    },

    // onLoad () {},

    start () {
        this.init();
    },
    /**
     * 初始化
     * @return {[type]} [description]
     */
    init(){
        this.initData();
    },
    /**
     * 初始化数据
     * @return {[type]} [description]
     */
    initData(){
        //背景旋转
        this.bg.node.runAction(cc.repeatForever(cc.rotateBy(100,360)));

        //重置websocket
        Global.socket.sock.parent = this;
        Global.socket.sock.onmessage = this.onMessage;
    },
    /**
     * 接收消息
     * @return {[type]} [description]
     */
    onMessage(result){
        cc.log("接收消息:"+result.data);

        var self = this.parent;

        var message = JSON.parse(result.data);

        if(message.type==4){
            cc.log("对手准备完成");

            self.isReady = true;
        }
    },
    update (dt) {
        if(this.updateIndex%this.speed==0){
            if(this.process.progress<1.0){
                this.loadingText.string = "资源载入中("+Math.ceil(this.process.progress*100)+"%)..."
                this.process.progress += dt;
            }else if(!this.isSend){
                this.isSend = true;
                message.type=4;
                message.content="准备完成";
                Global.socket.sendData(message);
            }else if(this.isSend&&this.isReady&&!this.isGame){
                this.isGame = true;
                cc.director.loadScene("game");
            }
        }
        this.updateIndex++;
    },
});
